/* JTextFieldFixed
 * 
 * Date: 22/2/2012
 * Author: Jorge de Grandes Fernández-Galiano
 * 
 * Description:
 * 		It is an extension of JTextField with the addition of a fixed maximum number of characters.
 * 		For unlimited number of characters use JTextField instead.
 * 		If max_length is set to 0 or below it will be ignored
 */

package test.jframe;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JTextField;

public class JTextFieldFixed extends JTextField implements KeyListener {

	private static final long serialVersionUID = 1L;

	int max_length = 0;
	
	public JTextFieldFixed(int max) {
		super();
		if (max > 0) max_length = max;
		addKeyListener(this);
	}
	
	public JTextFieldFixed(int columns, int max) {
		super(columns);
		if (max > 0) max_length = max;
		addKeyListener(this);
	}

	public JTextFieldFixed(String text, int max) {
		super(text);
		if (max > 0) max_length = max;
		addKeyListener(this);
	}

	public JTextFieldFixed(String text, int columns, int max) {
		super(text, columns);
		if (max > 0) max_length = max;
		addKeyListener(this);
	}

	protected void setMaximumLength(int max) {
		if (max > 0) max_length = max;
	}

	@Override
	public void keyTyped(KeyEvent e) {
		JTextField tf = (JTextField) e.getSource();
		if ((max_length > 0) && (tf.getText().length() >= max_length))
			tf.setText(tf.getText().substring(0, max_length-1));
	}

	@Override
	public void keyPressed(KeyEvent arg0) {
	}

	@Override
	public void keyReleased(KeyEvent arg0) {
	}

}
